<?php
/**
 * Created by: i@fedax.cn
 * Date: 2018/7/29 0:16
 */

namespace app\admin\model;

use think\Db;
use think\facade\Log;

class Recharge extends DataBase
{
    protected $autoWriteTimestamp = true;

    //获取器
//    public function getCreateTimeAttr($value){
//        return date('Y-m-d H:i:s', $value);
//    }
    public function getStateAttr($value)
    {
        $status = [1 => '支付宝', 2 => '微信', 3 => '苹果内购', 4 => '收单宝', 5 => '浦发银行', 6 => '通联支付', 7 => '绯闻广州'];

        return $status[$value];
    }

    /**
     * Notes: 充值数据
     * User: 王俊成
     * Date: 2018/10/30
     * Time: 13:54
     *
     * @return array
     */
//    public function recharge(){
//        $allMoney = $this->where('status',2)->sum('amount');
//        $wechatMoney = $this->where([['status','=',2],['state','=',2]])->sum('amount');
//        $alipayMoney = $this->where([['status','=',2],['state','=',1]])->sum('amount');
//        $todayRecharge = $this->where('status',2)->whereBetweenTime('create_time',strtotime(date('Y-m-d')),strtotime(date('Y-m-d').' 23:59:59'))->sum('amount');
//        $successWithdrawal = Withdrawal::where('status',3)->sum('real_amount');
//        //除去提现后的剩余
//        $realMoney = $allMoney -  $successWithdrawal;
//        return [
//            'allMoney' => $allMoney,
//            'wechatMoney' => $wechatMoney,
//            'alipayMoney' => $alipayMoney,
//            'todayRecharge' => $todayRecharge,
//            'realMoney' => $realMoney
//        ];
//
//    }

    /**
     * 获取代充记录
     *
     * @return void
     *
     * @example
     *
     * @author Cucumber
     *
     * @since
     */
    public function agentRechargeRecord()
    {
        $key = input('key');
        $value = input('value');
        $start_time = input('start_time');
        $end_time = input('end_time');

        $page_config = [
             'page' => input('pageNum', 1),
             'list_rows' => input('limit', 10),
             'query' => [
                 $key => $value,
             ],
         ];
        $agentRechargeModel = new AgentRecharge();

        $data = $agentRechargeModel->order('created_at desc');
        if ($value) {
            $data->where($key, $value);
        }
        if ($start_time) {
            $data->where('created_at', '>=', strtotime($start_time));
        }
        if ($end_time) {
            $data->where('created_at', '<=', strtotime($end_time));
        }
        $data = $data->paginate($page_config);
        $receiveIds = [];
        $recahrgeIds = [];
        foreach ($data as $key => $item) {
            $receiveIds[] = $item['receive_user_id'];
            $recahrgeIds[] = $item['recharge_user_id'];
        }

        $receiveUsers = User::whereIn('user_id', $receiveIds)->field('user_id,u_number,nickname')->select();
        $rechargeUsers = User::whereIn('user_id', $recahrgeIds)->field('user_id,u_number,nickname')->select();
        $receiveUidToInfo = [];
        $rechargeUidToInfo = [];

        foreach ($receiveUsers as $key => $user) {
            $receiveUidToInfo[$user['user_id']] = ['nickname' => preg_replace_callback('/@E(.{6}==)/', function ($r) {
                return base64_decode($r[1]);
            }, $user['nickname']), 'u_number' => $user['u_number']];
        }
        foreach ($rechargeUsers as $key => $user) {
            $rechargeUidToInfo[$user['user_id']] = ['nickname' => preg_replace_callback('/@E(.{6}==)/', function ($r) {
                return base64_decode($r[1]);
            }, $user['nickname']), 'u_number' => $user['u_number']];
        }
        // var_dump($receiveUidToInfo);
        foreach ($data as $key => $value) {
            $data[$key]['recharge_nickname'] = isset($rechargeUidToInfo[$value['recharge_user_id']]) ? $rechargeUidToInfo[$value['recharge_user_id']]['nickname'] : '';
            $data[$key]['nickname'] = isset($receiveUidToInfo[$value['receive_user_id']]) ? $receiveUidToInfo[$value['receive_user_id']]['nickname'] : '';
            $data[$key]['receive_user_id'] = isset($receiveUidToInfo[$value['receive_user_id']]) ? $receiveUidToInfo[$value['receive_user_id']]['user_id'] : '';
            $data[$key]['recharge_diamonds'] = $value['recharge_diamonds'];
            $data[$key]['created_at'] = date('Y-m-d H:i:s', $value['created_at']);
        }

        return $data;
    }

    /**
     * @return array
     *               自定义查询
     * @user 帅帅 吴
     */
    public function rechargeCount()
    {
        $type = input('get.type');
        $start_time = strtotime(input('get.start_time'));
        $end_time = strtotime(input('get.end_time'));
        $user_id = input('get.uid');

        if (!empty($start_time)) {
            $map[] = ['created_at', 'egt', $start_time];
        }
        if (!empty($end_time)) {
            $map[] = ['created_at', 'lt', $end_time];
        }
        if (!empty($user_id)) {
            $map[] = ['user_id', 'eq', $user_id];
        }
        switch ($type) {
            case 1:
                $map[] = ['status', 'eq', 2];
                $data = $this->where($map)->sum('amount');
                break;
            case 2:
                $map[] = ['status', 'eq', 2]; $map[] = ['state', 'eq', 2];
                $data = $this->where($map)->sum('amount');
                break;
            case 3:
                $map[] = ['status', 'eq', 2]; $map[] = ['state', 'eq', 1];
                $data = $this->where($map)->sum('amount');
                break;
            case 5:
                $data = $this->where('status', 'eq', 2)->whereBetweenTime('created_at', strtotime(date('Y-m-d')), strtotime(date('Y-m-d') . ' 23:59:59'))->sum('amount')
                ; break;
            case 4:
                $map[] = ['status', 'eq', 2];
                $allMoney = $this->where($map)->sum('amount');
                array_pop($map); $map[] = ['status', 'eq', 3];
                $successWithdrawal = Withdrawal::where($map)->sum('real_amount');
                $data = $allMoney - $successWithdrawal;
                break;
        }

        return ['code' => 100, 'data' => $data];
    }

    /**
     * Notes: 查询的充值金额
     * User: 王俊成
     * Date: 2018/10/30
     * Time: 14:20
     *
     * @return float
     */
    public function rechargeCountData()
    {
        $uid = input('get.uid');
        $startTime = input('get.start_time');
        $endTime = input('get.end_time');
        $map[] = ['status', '=', 2];
        if (!empty($startTime) && !empty($endTime)) {
            $startTime = strtotime($startTime);
            $endTime = strtotime($endTime);
            if ($startTime <= $endTime) {
                $map[] = ['create_time', 'between', [$startTime, $endTime]];
            } else {
                $map[] = ['create_time', 'between', [$endTime, $startTime]];
            }
        } elseif (!empty($startTime)) {
            $startTime = strtotime($startTime);
            $map[] = ['create_time', '>=', $startTime];
        } elseif (!empty($endTime)) {
            $endTime = strtotime($endTime);
            $map[] = ['create_time', '<=', $endTime];
        }
        if (!empty($uid) || '0' == $uid) {
            $user_id = User::where('u_id', $uid)->value('id');
            if ($user_id) {
                $map[] = ['user_id', '=', $user_id];
            } else {
                $map[] = ['user_id', '=', 0];
            }
        }

        return $this->where($map)->sum('amount');
    }

    /**
     * Notes: 充值记录
     * User: 王俊成
     * Date: 2018/10/29
     * Time: 17:10
     *
     * @throws \think\exception\DbException
     *
     * @return \think\Paginator|null
     */
    public function rechargeData()
    {
        $key = input('get.key');
        $value = input('get.value');
        $startTime = input('get.start_time');
        $endTime = input('get.end_time');
        $order = ['created_at' => 'desc'];
        $page_config = [
            'page' => input('get.pageNum', 1),
            'list_rows' => input('get.limit', 10),
        ];
        $map[] = ['status', '=', 2];
        if (!empty($startTime) && !empty($endTime)) {
            $startTime = strtotime($startTime);
            $endTime = strtotime($endTime);
            if ($startTime <= $endTime) {
                $map[] = ['created_at', 'between', [$startTime, $endTime]];
            } else {
                $map[] = ['created_at', 'between', [$endTime, $startTime]];
            }
        } elseif (!empty($startTime)) {
            $startTime = strtotime($startTime);
            $map[] = ['created_at', '>=', $startTime];
        } elseif (!empty($endTime)) {
            $endTime = strtotime($endTime);
            $map[] = ['created_at', '<=', $endTime];
        }
        if ('order_no' != $key && $value) {
            $user_id = User::where('u_number', $value)->value('user_id');
            if ('receive_user_id' == $key) {
                $map[] = ['user_id', 'eq', $user_id];
            }
            if ('send_user_id' == $key) {
                $map[] = ['send_user_id', 'eq', $user_id];
            }
        }
        if ('order_no' == $key && $value) {
            $map[] = ['order_no', 'eq', $value];
        }
        $data = $this->where($map)->order($order)->paginate($page_config);
        if ($data) {
            foreach ($data as $key => $value) {
                $value['u_id'] = get_uid($value['user_id']);
                $value['send_user_uid'] = get_uid($value['send_user_id']);
                $value['user_nickname'] = get_user_name($value['user_id']);
                $value['send_user_nickname'] = get_user_name($value['send_user_id']);
                $data[$key] = $value;
            }
        }

        return $data;
    }

    /**
     * Notes: 充值记录数据导出
     * User: 王俊成
     * Date: 2018/10/29
     * Time: 18:20
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function rechargeDataExport()
    {
        //  halt(input('get.'));
        $uid = input('get.uid');
        $startTime = input('get.start_time');
        $endTime = input('get.end_time');
        $map[] = ['status', '=', 2];
        if (!empty($startTime) && !empty($endTime)) {
            $startTime = strtotime($startTime);
            $endTime = strtotime($endTime);
            if ($startTime <= $endTime) {
                $map[] = ['create_time', 'between', [$startTime, $endTime]];
            } else {
                $map[] = ['create_time', 'between', [$endTime, $startTime]];
            }
        } elseif (!empty($startTime)) {
            $startTime = strtotime($startTime);
            $map[] = ['create_time', '>=', $startTime];
        } elseif (!empty($endTime)) {
            $endTime = strtotime($endTime);
            $map[] = ['create_time', '<=', $endTime];
        }
        if (!empty($uid) || '0' == $uid) {
            $user_id = User::where('u_id', $uid)->value('id');
            if ($user_id) {
                $map[] = ['user_id', '=', $user_id];
            }
        }
        // halt($map);
        $data = $this->where($map)->order('create_time', 'desc')->select();
        if ($data) {
            foreach ($data as $key => $value) {
                $value['u_id'] = get_uid($value['user_id']);
                $value['pay_uid'] = get_uid($value['send_user_id']);
                $value['nickname'] = filterEmoji(get_user_name($value['user_id']));
                $value['pay_nickname'] = filterEmoji(get_user_name($value['send_user_id']));
                $data[$key] = $value;
            }
        }
        //  halt($data);
        $fileName = '充值记录-' . date('Y-m-d');
        $remarkData = '';
        $cellTitle = [
            ['u_id', '充值方id'],
            ['nickname', '充值方'],
            ['pay_uid', '付款方id'],
            ['pay_nickname', '付款方'],
            ['order_no', '订单号'],
            ['amount', '充值金额'],
            ['state', '充值方式'],
            ['diamonds', '获得钻石'],
            ['gold', '获得金币'],
            ['create_time', '充值时间'],
        ];
        $excelObj = new \app\common\api\Excel();
        $excelObj->exportExcel($fileName, $remarkData, $cellTitle, $data);
    }

    /**
     * Notes: 查询某个用户的充值记录
     * User: 王俊成
     * Date: 2018/11/5
     * Time: 14:33
     *
     * @throws \think\exception\DbException
     *
     * @return \think\Paginator
     */
    public function rechargeInfo()
    {
        $user_id = input('get.user_id');
        $pageConfig = [
            'list_rows' => 25,
            'page' => input('get.page', 1),
            'query' => [
                'user_id' => $user_id,
            ],
        ];

        return $this->where([['user_id', '=', $user_id], ['status', '=', 2]])->order('created_at DESC')->paginate($pageConfig);
    }

    //修改充值信息
    public function RechargeEditData()
    {
        $order_no = input('order_no');
        $receive_id = input('receive_id');
        $msg = input('msg');
        Db::connect('db_data')->startTrans();
        try {
            $rechargeInfo = $this->where('order_no', $order_no)->find();
            //修改前接收方信息
            $user_info = User::where('id', $rechargeInfo['user_id'])->find();
            //修改后接收方信息
            $receive_user_info = User::where('u_id', 'eq', $receive_id)->find();

            //判断修改后接收方是否存在
            if (empty($receive_user_info)) {
                return ['code' => '-100', 'msg' => '该用户不存在'];
            }

            //判断修改前接收方的钻石是否符合条件
            if ($user_info['diamonds'] < $rechargeInfo['diamonds']) {
                Db::connect('db_data')->rollback();

                return ['code' => -100, 'msg' => '接受方的钻石不足'];
            }
            //判断修改前接收方的金币是否符合条件
            if ($user_info['gold'] < $rechargeInfo['gold']) {
                Db::connect('db_data')->rollback();

                return ['code' => -100, 'msg' => '接受方的金币不足'];
            }
            //修改前接收方减去钻石和金币
            User::where('id', 'eq', $rechargeInfo['user_id'])->setDec('diamonds', $rechargeInfo['diamonds']);
            User::where('id', 'eq', $rechargeInfo['user_id'])->setDec('gold', $rechargeInfo['gold']);
            //修改后接收方增加钻石和金币
            User::where('u_id', 'eq', $receive_id)->setInc('diamonds', $rechargeInfo['diamonds']);
            User::where('u_id', 'eq', $receive_id)->setInc('gold', $rechargeInfo['gold']);

            //更新充值记录表信息
            $newData['user_id'] = $receive_user_info['id'];
            $newData['type'] = 2;
            $newData['msg'] = '修改前ID:' . $user_info['u_id'] . '%' . '操作员:' . session('admin_name') . '%修改理由:' . $msg . '%修改时间:' . date('Y-m-d H:i:s');

            $this->where('order_no', $order_no)->update($newData);

            //全局的钻石收支表
            DiamondsAccount($user_info['id'], 2, 21, $rechargeInfo['diamonds'], '个钻石');
            DiamondsAccount($receive_user_info['id'], 1, 22, $rechargeInfo['diamonds'], '个钻石');

            Db::connect('db_data')->commit();

            return ['code' => 100, 'msg' => '修改成功'];
        } catch (\Exception $e) {
            Db::connect('db_data')->rollback();

            return ['code' => 100, 'msg' => '修改成功' . $e->getMessage()];
        }
    }

    //充错了用户，客服改回
    public function changeRechargeObject()
    {
        $page_config = [
            'page' => input('offset', 1),
            'list_rows' => input('limit', 10),
        ];
        $map = [];
        $map[] = ['type', 'eq', 2];
        $start_time = strtotime(input('start_time'));
        $end_time = strtotime(input('end_time'));
        if ($start_time) {
            $map[] = ['created_at', 'egt', $start_time];
        }
        if ($end_time) {
            $map[] = ['created_at', 'elt', $end_time];
        }
        if ($start_time && $end_time) {
            $map[] = ['created_at', 'between', [$start_time, $end_time]];
        }

        $key = input('key');
        $value = input('value');

        if ('order_no' != $key && $value) {
            $user_id = User::where('u_number', $value)->value('user_id');
            if ('u_id' == $key) {
                $map[] = ['user_id', 'eq', $user_id];
            }
            if ('prev_uid' == $key) {
                $map[] = ['msg', 'like', '%' . $value . '%'];
            }
            if ('send_user_id' == $key) {
                $map[] = ['send_user_id', 'eq', $user_id];
            }
        }
        if ('order_no' == $key && $value) {
            $map[] = ['order_no', 'eq', $value];
        }

        $order = ['created_at' => 'DESC'];

        $data = $this->where($map)->order($order)->paginate($page_config);

        foreach ($data as $key => $value) {
            $value['u_id'] = get_uid($value['user_id']);
            $value['send_user_uid'] = get_uid($value['send_user_id']);
            $value['user_nickname'] = get_user_name($value['user_id']);
            $value['send_user_nickname'] = get_user_name($value['send_user_id']);
            $arr = explode('%', $value['msg']);
            $value['prev_uid'] = substr($arr[0], strpos($arr[0], ':') + 1);
            $value['admin_name'] = substr($arr[1], strpos($arr[1], ':') + 1);
            $value['msg'] = substr($arr[2], strpos($arr[2], ':') + 1);
            $value['update_at'] = substr($arr[3], strpos($arr[3], ':') + 1);
            $value['prev_nickname'] = User::where('u_id', $value['prev_uid'])->value('nickname');
            $data[$key] = $value;
        }
        //dump($data);
        return $data;
    }
}
